package com.syni.mdd.yhd.common.all.controller.protect;

import com.syni.mdd.sjb.common.component.utils.common.utils.BeanUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.ParamsMap;
import com.syni.mdd.sjb.common.component.utils.common.utils.RequestHeaderData;
import com.syni.mdd.sjb.common.component.utils.common.utils.ResultMapHelper;
import com.syni.mdd.sjb.common.component.utils.common.annotations.CheckParams;
import com.syni.mdd.sjb.common.component.utils.common.annotations.EntranceCheck;
import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.constants.ResultCode;
import com.syni.mdd.yhd.common.all.constants.ResultMsg;
import com.syni.mdd.yhd.common.all.dto.requestDto.BmsReportErrorReDto;
import com.syni.mdd.yhd.common.all.dto.requestDto.video.BmsVideoReDto;
import com.syni.mdd.yhd.common.all.entity.BmsVideo;
import com.syni.mdd.yhd.common.all.entity.bo.user.CheckUserBo;
import com.syni.mdd.yhd.common.all.service.BmsUserService;
import com.syni.mdd.yhd.common.all.service.BmsVideoService;
import com.syni.mdd.yhd.common.all.utils.*;
import com.syni.mdd.yhd.common.all.validationGroup.GroupCheckPaging;
import com.syni.mdd.yhd.common.all.validationGroup.GroupFind;
import com.syni.mdd.yhd.common.all.vo.rp.video.GetVideoListV2Vo;
import lombok.extern.log4j.Log4j2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/video")
@Log4j2
public class BmsVideoController {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    BmsVideoService bmsVideoService;

    @Autowired
    BmsUserService bmsUserService;

    @Autowired
    ApplicationContext applicationContext;

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * @Description: 获取视频信息（返回一个剩余存redis）
     * @Param: open_id
     * @Param: latitude（纬度）
     * @Param: longitude（经度）
     * @return: Map
     * @Author: cfx
     * @Date: 2019/4/9
     */
    @CheckParams(params = {"latitude","longitude","addr_city","addr_district"})
    //@ControllerLog(operationAction = "获取视频")
    @PostMapping("/getVideoList")
    public Map<String, Object> videoList(@RequestBody Map<String,Object> paramsMap){
        CheckUserBo checkUserBo = RequestParamUtils.checkUserBo();
        String userIdentify;
        if(!checkUserBo.getCheckStatus().equals(ResultCode.CODE_NORMAL)){
            if(paramsMap.containsKey("virtualUserId") && StringUtils.checkNullAndEmpty(paramsMap.get("virtualUserId"))
                    && paramsMap.get("virtualUserId").toString().startsWith(BmsVideoService.visitorPrfix)){
                userIdentify = paramsMap.get("virtualUserId").toString();
            }else {
                long userid = System.currentTimeMillis() + Thread.currentThread().getId();
                userIdentify = String.format("X999%s",userid);
            }
        } else {
            userIdentify = checkUserBo.getUserId();
        }
        String latitude = paramsMap.get("latitude").toString();
        String longitude = paramsMap.get("longitude").toString();
        String addrCity = paramsMap.get("addr_city").toString();
        String addrDistrict = paramsMap.get("addr_district").toString();
        Integer isInArea = 1;
        if(paramsMap.containsKey("isInArea") && StringUtils.checkNullAndEmpty(paramsMap.get("isInArea"))){
            isInArea = Integer.parseInt(paramsMap.get("isInArea").toString());
        }
        /*List<BmsVideo> bmsVideos = bmsVideoService.getBmsVideoListSecond(userIdentify,latitude,
                longitude,addrCity,addrDistrict);*/
        List<BmsVideo> bmsVideos = new LinkedList<>();
        try {
//            bmsVideos = bmsVideoService.getBmsVideoListByAlgorithm(userIdentify,latitude,
//                    longitude,addrCity,addrDistrict,isInArea);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            bmsVideos = bmsVideoService.getBmsVideoListSecond(userIdentify,latitude,
                    longitude,addrCity,addrDistrict);
        }
        if(bmsVideos.size() == 0){
            bmsVideos = bmsVideoService.getBmsVideoListSecond(userIdentify,latitude,
                    longitude,addrCity,addrDistrict);
        }
        Map<String,Object> userData = new HashMap<>();
        userData.put("userid",userIdentify);
        userData.put("count",bmsVideos.size());
        return ResultMapHelper.success(bmsVideos,userData,"获取成功");
    }

    /**
     * @Description: 获取视频信息（返回一个剩余存redis）
     * @Param: open_id
     * @Param: latitude（纬度）
     * @Param: longitude（经度）
     * @return: Map
     * @Author: cfx
     * @Date: 2019/4/9
     */
    @PostMapping("/getVideoList/v2")
    public Map<String, Object> videoList_v2(@RequestBody ParamsMap paramsMap){
        CheckUserBo checkUserBo = RequestParamUtils.checkUserBo();
        //默认使用设备标识
        String userIdentify = RequestHeaderData.getRequestHeaderData().getString("devid");
        if(checkUserBo.getCheckStatus().equals(ResultCode.CODE_NORMAL)){
            userIdentify = checkUserBo.getUserId();
        }
        String latitude = paramsMap.getString("latitude","");
        String longitude = paramsMap.getString("longitude","");
        String addrCity = paramsMap.getString("addr_city","");
        String addrDistrict = paramsMap.getString("addr_district","");
        Integer isInArea = 1;
        if(paramsMap.containsKey("isInArea") && StringUtils.checkNullAndEmpty(paramsMap.get("isInArea"))){
            isInArea = Integer.parseInt(paramsMap.getString("isInArea"));
        }
        List<BmsVideo> bmsVideos = new LinkedList<>();
        try {
            bmsVideos = bmsVideoService.getBmsVideoListByAlgorithm(userIdentify,latitude,
                    longitude,addrCity,addrDistrict,isInArea);
        }catch (Exception e){
            log.error(e.getMessage(),e);
            bmsVideos = bmsVideoService.getBmsVideoListSecond(userIdentify,latitude,
                    longitude,addrCity,addrDistrict);
        }
        if(bmsVideos.size() == 0){
            bmsVideos = bmsVideoService.getBmsVideoListSecond(userIdentify,latitude,
                    longitude,addrCity,addrDistrict);
        }
        Map<String,Object> userData = new HashMap<>();
        userData.put("count",bmsVideos.size());
        List<GetVideoListV2Vo> getVideoListV2Vos = new ArrayList<>();
        bmsVideos.forEach(bv -> {
            GetVideoListV2Vo getVideoListV2Vo = BeanUtils.copyProperties(bv,GetVideoListV2Vo.class);
            getVideoListV2Vo.setBusiness(BeanUtils.copyProperties(bv.getBmsBusiness(),GetVideoListV2Vo.BusinessRpVo.class));
            if(StringUtils.isNotBlank(bv.getCloudFileTranscodeH5Url())){
                getVideoListV2Vo.setCloudFileUrl(bv.getCloudFileTranscodeH5Url());
            }
            if(StringUtils.isBlank(bv.getCloudFileTranscodeH5Url()) && StringUtils.isNotBlank(bv.getCloudFileTranscode30Url())){
                getVideoListV2Vo.setCloudFileUrl(bv.getCloudFileTranscode30Url());
            }
            getVideoListV2Vos.add(getVideoListV2Vo);
        });
        return ResultMapHelper.success(getVideoListV2Vos,userData,"获取成功");
    }

    /**
     * @Description: 获取下一个视频信息（从redis中取）
     * @Param: open_id
     * @return: Map
     * @Author: cfx
     * @Date: 2019/4/9
     */
    //@ControllerLog(operationAction = "获取下一个视频")
    @PostMapping("/getNextVideo")
    public Map<String, Object> nextVideo(@RequestBody Map<String,Object> paramsMap){
        RequestHeaderData requestHeaderData = new RequestHeaderData();
        String userId = null;
        if(requestHeaderData.containsKey("client")
                && StringUtils.checkNullAndEmpty(requestHeaderData.get("client"))){
            int client = requestHeaderData.getInteger("client");
            if(client == Constants.IOS_CLIENT || client == Constants.ANDROID_CLIENT){
                if(!requestHeaderData.containsKey("userid")){
                    return ResultMapHelper.failure("缺少userid");
                }
                userId = requestHeaderData.getString("userid");
            }
        }else {
            if(!paramsMap.containsKey("open_id")){
                return ResultMapHelper.failure("缺少参数open_id");
            }
            userId = TokenManager.getUserId(paramsMap.get("open_id").toString()).toString();
            if(userId == null){
                return ResultMapHelper.failure("用户不存在");
            }
        }
        List<BmsVideo> bmsVideos = bmsVideoService.getNextVideo(userId);
        /*if(bmsVideos == null || bmsVideos.size() == 0){
            return ResultMapHelper.failure("无视频数据，请重新刷新");
        }*/

        return ResultMapHelper.success(bmsVideos,"获取成功");
    }


    /**
     * @Description: 获取下一个视频信息（从redis中取）
     * @Param: open_id
     * @return: Map
     * @Author: cfx
     * @Date: 2019/4/9
     */
    //@ControllerLog(operationAction = "获取下一个视频")
    @PostMapping("/getNextVideo/v2")
    public Map<String, Object> nextVideo_v2(@RequestBody ParamsMap paramsMap){
        CheckUserBo checkUserBo = RequestParamUtils.checkUserBo();
        //默认使用设备标识
        String userIdentify = RequestHeaderData.getRequestHeaderData().getString("devid");
        if(checkUserBo.getCheckStatus().equals(ResultCode.CODE_NORMAL)){
            userIdentify = checkUserBo.getUserId();
        }
        List<BmsVideo> bmsVideos = bmsVideoService.getNextVideo(userIdentify);
        List<GetVideoListV2Vo> getVideoListV2Vos = new ArrayList<>();
        bmsVideos.forEach(bv -> {
            GetVideoListV2Vo getVideoListV2Vo = BeanUtils.copyProperties(bv,GetVideoListV2Vo.class);
            getVideoListV2Vo.setBusiness(BeanUtils.copyProperties(bv.getBmsBusiness(),GetVideoListV2Vo.BusinessRpVo.class));
            if(StringUtils.isNotBlank(bv.getCloudFileTranscodeH5Url())){
                getVideoListV2Vo.setCloudFileUrl(bv.getCloudFileTranscodeH5Url());
            }
            if(StringUtils.isBlank(bv.getCloudFileTranscodeH5Url()) && StringUtils.isNotBlank(bv.getCloudFileTranscode30Url())){
                getVideoListV2Vo.setCloudFileUrl(bv.getCloudFileTranscode30Url());
            }
            getVideoListV2Vos.add(getVideoListV2Vo);
        });
        return ResultMapHelper.success(bmsVideos,"获取成功");
    }

    /**
     * @Description 搜索商家视频信息
     * @Param: searchText（搜索内容）
     * @Param: page（页数）
     * @return: Map
     * @Author: cfx
     * @Date: 2019/4/9
     */
    @CheckParams(params = {"page"})
    //@ControllerLog(operationAction = "搜索商家视频")
    @PostMapping("/getSearchVideo")
    public Map<String,Object> getSearchVideo(@RequestBody Map<String,Object> paramsMap){
        CheckUserBo checkUserBo = RequestParamUtils.checkUserBo();
        String userIdentify = null;
        if(checkUserBo.getCheckStatus().equals(ResultCode.CODE_NORMAL)){
            userIdentify = checkUserBo.getUserId();
        }
        Integer businessId = null;
        if(paramsMap.containsKey("business_id") && !"".equals(paramsMap.get("business_id").toString())){
            businessId = Integer.parseInt(paramsMap.get("business_id").toString());
        }
        String latitude = null;
        if(paramsMap.containsKey("latitude")){
            latitude = paramsMap.get("latitude").toString();
        }
        String longitude = null;
        if(paramsMap.containsKey("longitude")){
            longitude = paramsMap.get("longitude").toString();
        }
        String searchText = null;
        if(paramsMap.containsKey("search_text") && !"".equals(paramsMap.get("search_text").toString())){
            searchText = paramsMap.get("search_text").toString();
        }
        Integer page = Integer.parseInt(paramsMap.get("page").toString());
        Integer pageSize = null;
        if(paramsMap.containsKey("page_size")){
            pageSize = Integer.parseInt(paramsMap.get("page_size").toString());
        }
        return bmsVideoService.searchVideo(userIdentify,businessId,latitude,longitude,
                searchText,page,pageSize);
    }

    /**
     * @Description 视频详情
     * @return: Map
     * @Author: cfx
     * @Date: 2019/4/9
     */
    //@ControllerLog(operationAction = "搜索商家视频")
    @CheckParams
    @PostMapping("/getVideoDetail")
    public Map<String,Object> getVideoDetail(@RequestBody ParamsMap paramsMap) throws Exception {
        Map<String,Object> checkRet = RequestParamUtils.checkAuthor(paramsMap);
        String userIdentify = null;
        if(checkRet.get("status").toString().equals(ResultCode.CODE_NORMAL)){
            userIdentify = checkRet.get("userIdentify").toString();
        }
        String videoCode = paramsMap.getString("videoCode");
        Integer videoId;
        if(videoCode != null){
            videoId = Integer.parseInt(DESUtil.decrypt(videoCode));
        }else {
            videoId = paramsMap.getInteger("videoId");
            if(videoId == null){
                videoId = paramsMap.getInteger("video_id");
            }
        }
        String latitude = paramsMap.getString("latitude");
        String longitude = paramsMap.getString("longitude");
        return bmsVideoService.findDetailVideo(userIdentify,latitude,longitude,videoId);
    }

    @CheckParams(params = {"page_num","page_size"})
    @PostMapping("/getMyVideo")
    public Map<String,Object> getMyVideo(@RequestBody Map<String,Object> paramsMap){
        String userIdentify;
        String headUserId = null;
        if(paramsMap.containsKey("user_id") && StringUtils.checkNullAndEmpty(paramsMap.get("user_id"))){
            userIdentify = paramsMap.get("user_id").toString();
            //尝试从请求头中获取请求用户
            Map<String,Object> checkRet = RequestParamUtils.checkAuthor(paramsMap);
            if(ResultCode.CODE_NORMAL.equals(checkRet.get("status").toString())){
                headUserId = checkRet.get("userIdentify").toString();
            }
        }else {
            CheckUserBo checkUserBo = RequestParamUtils.checkUserBo();
            if(!checkUserBo.getCheckStatus().equals(ResultCode.CODE_NORMAL)){
                return ResultMapHelper.success(null, ResultMsg.HAND_SUCCESS);
            }
            userIdentify = checkUserBo.getUserId();
            headUserId = userIdentify;
        }
        //纬度
        String latitude = null;
        if(paramsMap.containsKey("latitude") && !"".equals(paramsMap.get("latitude").toString())){
            latitude = paramsMap.get("latitude").toString();
        }
        //经度
        String longitude = null;
        if(paramsMap.containsKey("longitude") && !"".equals(paramsMap.get("longitude").toString())){
            longitude = paramsMap.get("longitude").toString();
        }
        Integer pageNum = Integer.parseInt(paramsMap.get("page_num").toString());
        Integer pageSize = Integer.parseInt(paramsMap.get("page_size").toString());
        return bmsVideoService.findMyVideo(userIdentify,latitude,longitude,pageNum,pageSize,headUserId);
    }

    @PostMapping("/releaseVideo")
    @CheckParams(checkAuth = true,params = {"video_file_id","video_file_url"})
    public Map<String,Object> releaseVideo(@RequestBody ParamsMap paramsMap){
        return bmsVideoService.releaseVideo(paramsMap);
    }


    /*@PostMapping("/similarBusinessRecommend")
    @CheckParams(params = {"video_id"})
    public Map<String,Object> similarBusiznessRecommend(@RequestBody Map<String,Object> paramsMap){
        Integer videoId = Integer.parseInt(paramsMap.get("video_id").toString());
        return bmsVideoService.similarBusinessRecommend(videoId);
    }*/

    @PostMapping("/delVideo")
    @CheckParams(checkAuth = true,params = {"video_id"})
    public Map<String,Object> delVideo(@RequestBody Map<String,Object> paramsMap){
        Integer userId = Integer.parseInt(paramsMap.get("userIdentify").toString());
        Integer videoId = Integer.parseInt(paramsMap.get("video_id").toString());
        return bmsVideoService.delVideo(userId,videoId);
    }


    /**
     * @Description 获取用户关注的视频
     * @Author: cfx
     * @Date: 2019/7/9
     */
    @PostMapping("/getMyFocusVideo")
    @CheckParams(checkAuth = true,params = {"pageNum","pageSize"})
    public Map<String,Object> getMyFocusVideo(@RequestBody Map<String,Object> paramsMap){
        Integer userId = Integer.parseInt(paramsMap.get("userIdentify").toString());
        Integer pageNum = Integer.parseInt(paramsMap.get("pageNum").toString());
        Integer pageSize = Integer.parseInt(paramsMap.get("pageSize").toString());
        String latitude = null;
        if(paramsMap.containsKey("latitude") && StringUtils.checkNullAndEmpty(paramsMap.get("latitude"))){
            latitude = paramsMap.get("latitude").toString();
        }
        String longitude = null;
        if(paramsMap.containsKey("longitude") &&  StringUtils.checkNullAndEmpty(paramsMap.get("longitude"))){
            longitude = paramsMap.get("longitude").toString();
        }
        return bmsUserService.getMyFocusVideo(userId,pageNum,pageSize,latitude,longitude);
    }

    /**
     * @Description 获取附近视频
     * @Author: cfx
     * @Date: 2019/7/9
     */
    @PostMapping("/getNearVideo")
    @EntranceCheck
    public Map<String,Object> getNearVideo(@RequestBody @Validated({GroupFind.class, GroupCheckPaging.class}) BmsVideoReDto bmsVideoReDto){
        return bmsVideoService.getNearVideo(bmsVideoReDto);
    }

    /**
     * @Description 必看视频
     * @Author: cfx
     * @Date: 2019/7/9
     */
    @PostMapping("/mustSeeVideo")
    @EntranceCheck
    public Map<String,Object> mustSeeVideo(@RequestBody  BmsVideoReDto bmsVideoReDto){
        return bmsVideoService.mustSeeVideo(bmsVideoReDto);
    }






    /*@PostMapping("/uploadVideo")
    public Map<String,Object> uploadVideo(@RequestParam(name = "videoFile",required = true) MultipartFile uploadFile,
                                          @RequestParam(name = "back_music",required = false) String backMusic,
                                          @RequestParam(name = "business_name") String businessName,
                                          @RequestParam(name = "addr_city") String addrCity,
                                          @RequestParam(name = "addr_detail") String addrDetail,
                                          @RequestParam(name = "latitude") String latitude,@RequestParam(name = "longitude") String longitude,
                                          @RequestParam(name = "tags") String tags){
        bmsVideoService.upload(uploadFile);
        return null;
    }*/

    @PostMapping("/test")
    @EntranceCheck(checkAuth = true)
    public Map<String,Object> test(@RequestBody @Validated BmsReportErrorReDto bmsReportErrorReDto){
        System.out.println(bmsReportErrorReDto);
        return null;
    }

    @GetMapping("/test")
    @ResponseBody
    public String test(){
        //applicationContext.publishEvent(new VideoEvent("视频发布",null,1));
        //Map<String,Object> conditionMap = new HashMap<>();
        //String field = "5285890793010087855";
        //视频内容审核
        //TCCloudUtils.videoReview(field);
        //视频内容分析
        //TCCloudUtils.videoAnalysis(field);
        String apiKey = "apiMiDongDong0630.";
        Map<String,Object> headerMap = new HashMap<>();
        //当前时间搓
        Integer timestamp = (int)(System.currentTimeMillis() / 1000);
        String t = String.format("%08X", timestamp);
        //随机字符串
        String randomStr = CDNUtils.getStringRandom(8);
        //接口url
        String apiUrl = "/DSP_API/login/tryVisit";
        //生成md5sign
        String sign = WebUtils.MD5(apiKey + apiUrl + t + randomStr);
        System.out.println(sign);

        headerMap.put("rs",randomStr);
        headerMap.put("t",t);
        headerMap.put("sign",sign);
        System.out.println("rs :" + randomStr);
        System.out.println("t : " + t);
        System.out.println("sign: " + sign);
        Map<String,Object> paramsMap = new HashMap<>();
        String url = "http://localhost:8999/DSP_API/login/tryVisit";
        RestTemplateUtils.postForEntity(url,paramsMap,headerMap);
        return "abc";
    }

    @PostMapping("/videoCallBack")
    @ResponseBody
    public Map<String,Object> videoCallBack(@RequestBody String callBackJson){
        System.out.println("回调json: " + callBackJson);
        return ResultMapHelper.success();
    }


    @GetMapping("/videoDetail")
    @ResponseBody
    public Map<String,Object> videoDetail(Integer videoId){
        BmsVideo bmsVideo = new BmsVideo();
        return ResultMapHelper.success(bmsVideo);
    }

}
